package com.bw.dg.controller;

import com.bw.dg.common.CacheEnt;
import com.bw.dg.common.Result;
import com.bw.dg.common.StatusCode;
import com.bw.dg.pojo.User;
import com.bw.dg.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.apache.tools.ant.taskdefs.condition.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    //账号管理
    @RequestMapping("/findUserList")
    public List getUserList(@RequestParam(defaultValue = "")String mohu){
        System.out.println("用户名模糊:"+mohu);

        return userService.getUserList(mohu);
    }

    //登录
    @RequestMapping("/login")
    public Result login(@RequestBody User user) throws Exception {
        user = userService.login(user);
        if(user!=null){
            // 以当前访问机器的 id 作为session的健  127.0.0.1 255*255*255*255
            String address = InetAddress.getLocalHost().getHostAddress();

            CacheEnt.setUser(String.valueOf(user.getId()),user);
            return new Result(true, StatusCode.OK,"登录成功",user);
        }else {
            return new Result(false,StatusCode.LOGINERROR,"用户名或密码错误");
        }
    }

    //添加
    @RequestMapping("/add")
    public String add(@RequestBody User user){
        this.userService.add(user);
        return "成功";
    }

    //批删
    @RequestMapping("/del")
    public String del(@RequestParam("id") String id){
        String[] ids = id.split(",");
        for(String aa:ids){
            this.userService.del(aa);
        }
        return "删除成功";
    }

    //获取登录名
    @GetMapping("/getLoginer")
    public User getLoginer(HttpServletRequest request) throws  Exception{
        String address = InetAddress.getLocalHost().getHostAddress();
        // System.out.println(address);
        String token = request.getHeader("token");
        User user = CacheEnt.getUser(token);
        System.out.println(user);
        return user;
    }

    //修改密码
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update(@RequestBody User user){
         this.userService.update(user);
        return "成功";
    }

}
